package com.tan.androidtest.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.joker.api.Permissions4M;
import com.joker.api.wrapper.Wrapper;
import com.tan.androidtest.R;
import com.tan.androidtest.base.BaseActivity;
import com.tan.androidtest.bean.BussInfo;
import com.tan.androidtest.bean.OpenInfo;
import com.tan.androidtest.net.HttpCallBack;
import com.tan.androidtest.net.HttpResponse;
import com.tan.androidtest.util.DialogUtil;
import com.tan.androidtest.util.ToastUtil;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.List;

import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import okhttp3.Request;

/**
 * 测试BaseActivity
 */

public class TestBaseActivity extends BaseActivity {

    private static final int SENSORS_CODE = 11;
    private static final int LOCATION_CODE = 12;
    private static final int CALENDAR_CODE = 13;
    private static final int CALL_PHONE = 14;

    @Override
    public int initLayoutId() {
        return R.layout.activity_test_base_layout;
    }

    @Override
    public void initBundle() {
        super.initBundle();
        //requestPermission();
    }

    @Override
    public void initTitle(TextView tv_bar_left, TextView tv_bar_title, TextView tv_bar_right) {
        tv_bar_title.setText("测试BaseActivity");
    }

    @Override
    public void initView() {
        ImageView iv_test = findViewById(R.id.iv_test);
        Glide.with(this).load("https://ps.ssl.qhimg.com/t01bd0ccbdb3b4f870b.jpg").placeholder(R.mipmap.ic_launcher).into(iv_test);
        iv_test.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestPermission();
                /*if (selfPermissionGranted(TestBaseActivity.this, Manifest.permission.CALL_PHONE)) {
                    if (ActivityCompat.checkSelfPermission(TestBaseActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15213355341"));
                        startActivity(intent);
                    }
                }else {
                    ToastUtil.showToast(TestBaseActivity.this, "电话权限被拒绝");
                }*/


               /* if (ContextCompat.checkSelfPermission(TestBaseActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                    //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true
                    if (ActivityCompat.shouldShowRequestPermissionRationale(TestBaseActivity.this, Manifest.permission.CALL_PHONE)) {
                        Toast.makeText(TestBaseActivity.this, "你之前拒绝过此权限", Toast.LENGTH_SHORT).show();
                    } else {
                        //申请权限
                        ActivityCompat.requestPermissions(TestBaseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 100);
                    }
                } else {
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15213355341"));
                    startActivity(intent);
                    //ToastUtil.showToast(TestBaseActivity.this, "电话权限被拒绝");
                }*/
            }
        });
    }

    @Override
    public void initData() {
        //request();
        //request4M();
        request4mSingle();
        //rxRequest();
        //ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, 100);
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    /**
     * 测试动态申请权限
     */
    private void requestPermission() {
        RxPermissions r = new RxPermissions(this);
        r.requestEach(Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_CALENDAR,
                Manifest.permission.READ_CALL_LOG,
                Manifest.permission.READ_CONTACTS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.READ_SMS,
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA,
                Manifest.permission.CALL_PHONE,
                Manifest.permission.SEND_SMS).subscribe(new Consumer<Permission>() {
            @Override
            public void accept(Permission permission) throws Exception {
                if (permission.granted) {
                    // 用户已经同意该权限
                    Log.i("==--", permission.name + " 用户已经同意该权限");
                } else if (permission.shouldShowRequestPermissionRationale) {
                    // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                    Log.i("==--", permission.name + " 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框");
                } else {
                    // 用户拒绝了该权限，并且选中『不再询问』
                    Log.i("==--", permission.name + " 用户拒绝了该权限，并且选中『不再询问』");
                }
            }
        });


    }

    public boolean selfPermissionGranted(Context context, String permission) {
        PackageInfo info;
        try {
            info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            int targetSdkVersion = info.applicationInfo.targetSdkVersion;
            boolean ret = true;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                if (targetSdkVersion >= Build.VERSION_CODES.M) {
                    ret = context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED;
                } else {
                    ret = PermissionChecker.checkSelfPermission(context, permission) == PermissionChecker.PERMISSION_GRANTED;
                }
            }
            return ret;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 原生申请权限
     */
    private void request() {
        if (ContextCompat.checkSelfPermission(TestBaseActivity.this, Manifest.permission.CALL_PHONE) == PackageManager.PERMISSION_GRANTED) {
            try {
                Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15213355341"));
                startActivity(intent);
            } catch (Exception e) {
                e.printStackTrace();
                ToastUtil.showToast(TestBaseActivity.this, "电话权限被拒绝");
            }

//            //如果应用之前请求过此权限但用户拒绝了请求，此方法将返回 true
//            if (ActivityCompat.shouldShowRequestPermissionRationale(TestBaseActivity.this, Manifest.permission.CALL_PHONE)) {
//                Toast.makeText(TestBaseActivity.this, "你之前拒绝过此权限", Toast.LENGTH_SHORT).show();
//            } else {
//
//            }
        } else {
            //申请权限
            ActivityCompat.requestPermissions(TestBaseActivity.this, new String[]{Manifest.permission.CALL_PHONE}, 100);
            ToastUtil.showToast(TestBaseActivity.this, "电话权限被拒绝");
        }
    }

    /**
     * 请求网络
     */
    private void requestNet() {
        OkHttpUtils.post().url("http://node2.huwochuxing.com/requiement")
                .addParams("prov", "重庆市")
                .addParams("longitude", String.valueOf(106.491546))
                .addParams("latitude", String.valueOf(29.621993))
                .build().execute(new HttpCallBack<HttpResponse<OpenInfo>>() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
                DialogUtil.showLoadingDialog(TestBaseActivity.this);
            }

            @Override
            public void onResponse(HttpResponse<OpenInfo> response, int id) {
                DialogUtil.dismissLoadingDialog(TestBaseActivity.this);
                OpenInfo openInfo = response.getData();
                List<BussInfo> infos = openInfo.getOpenBizTypes();
                for (BussInfo info : infos) {
                    Log.i("==--", info.getName());
                }
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);

            }
        });
    }

    private void request4M() {
        Permissions4M.get(TestBaseActivity.this)
                .requestPermissions(Manifest.permission.BODY_SENSORS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_CALENDAR)
                .requestCodes(SENSORS_CODE, LOCATION_CODE, CALENDAR_CODE)
                .requestListener(new Wrapper.PermissionRequestListener() {
                    @Override
                    public void permissionGranted(int code) {
                        switch (code) {
                            case LOCATION_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "地理位置权限授权成功 in fragment with annotation");
                                break;
                            case SENSORS_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "传感器权限授权成功 in fragment with annotation");
                                break;
                            case CALENDAR_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "读取日历权限授权成功 in fragment with annotation");
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void permissionDenied(int code) {
                        switch (code) {
                            case LOCATION_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "地理位置权限授权失败 in fragment with annotation");
                                break;
                            case SENSORS_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "传感器权限授权失败 in fragment with annotation");
                                break;
                            case CALENDAR_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "读取日历权限授权失败 in fragment with annotation");
                                break;
                            default:
                                break;
                        }
                    }

                    @Override
                    public void permissionRationale(int code) {
                        switch (code) {
                            case LOCATION_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启地理位置权限 in fragment with annotation");
                                break;
                            case SENSORS_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启传感器权限 in fragment with annotation");
                                break;
                            case CALENDAR_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启读取日历权限 in fragment with annotation");
                                break;
                            default:
                                break;
                        }
                    }
                })
                .requestCustomRationaleListener(new Wrapper.PermissionCustomRationaleListener() {
                    @Override
                    public void permissionCustomRationale(int code) {
                        switch (code) {
                            case LOCATION_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启地理位置权限 in fragment with annotation");
                                Log.e("TAG", "permissionRationale: 请开启地理位置权限 ");

                                new AlertDialog.Builder(TestBaseActivity.this)
                                        .setMessage("地理位置权限权限申请：\n我们需要您开启地理位置权限(in fragment with " +
                                                "annotation)")
                                        .setPositiveButton("确定", new DialogInterface
                                                .OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Permissions4M.get(TestBaseActivity.this)
                                                        .requestOnRationale()
                                                        .requestPermissions(Manifest.permission
                                                                .ACCESS_FINE_LOCATION)
                                                        .requestCodes(LOCATION_CODE)
                                                        .request();
                                            }
                                        })
                                        .show();
                                break;
                            case SENSORS_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启传感器权限 in fragment with annotation");
                                Log.e("TAG", "permissionRationale: 请开启传感器权限 ");

                                new AlertDialog.Builder(TestBaseActivity.this)
                                        .setMessage("传感器权限申请：\n我们需要您开启传感器权限(in fragment with " +
                                                "annotation)")
                                        .setPositiveButton("确定", new DialogInterface
                                                .OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Permissions4M.get(TestBaseActivity.this)
                                                        .requestOnRationale()
                                                        .requestPermissions(Manifest.permission
                                                                .BODY_SENSORS)
                                                        .requestCodes(SENSORS_CODE)
                                                        .request();
                                            }
                                        })
                                        .show();
                                break;
                            case CALENDAR_CODE:
                                ToastUtil.showToast(TestBaseActivity.this, "请开启读取日历权限 in fragment with annotation");
                                Log.e("TAG", "permissionRationale: 请开启读取日历权限 ");

                                new AlertDialog.Builder(TestBaseActivity.this)
                                        .setMessage("日历权限申请：\n我们需要您开启日历权限(in fragment with " +
                                                "annotation)")
                                        .setPositiveButton("确定", new DialogInterface
                                                .OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                Permissions4M.get(TestBaseActivity.this)
                                                        .requestOnRationale()
                                                        .requestPermissions(Manifest.permission
                                                                .READ_CALENDAR)
                                                        .requestCodes(CALENDAR_CODE)
                                                        .request();
                                            }
                                        })
                                        .show();
                                break;
                            default:
                                break;
                        }

                    }
                })
                .request();
    }

    private void request4mSingle() {
        Permissions4M.get(TestBaseActivity.this)
                // 是否强制弹出权限申请对话框，建议为 true，默认为 true
                .requestForce(true)
                // 是否支持 5.0 权限申请，默认为 false
                // .requestUnderM(false)
                // 权限
                .requestPermissions(Manifest.permission.CALL_PHONE)
                // 权限码
                .requestCodes(CALL_PHONE)
                // 权限请求结果
                .requestListener(new Wrapper.PermissionRequestListener() {
                    @Override
                    public void permissionGranted(int code) {
                        //ToastUtil.show("读取通讯录权限成功 in activity with listener");
                        Log.i("==--", "读取通讯录权限成功 in activity with listener");
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15213355341"));
                        startActivity(intent);
                    }

                    @Override
                    public void permissionDenied(int code) {
                        //ToastUtil.show("读取通讯录权失败 in activity with listener");
                        Log.i("==--", "读取通讯录权失败 in activity with listener");
                    }

                    @Override
                    public void permissionRationale(int code) {
                        //ToastUtil.show("请打开读取通讯录权限 in activity with listener");
                        Log.i("==--", "请打开读取通讯录权限 in activity with listener");
                    }
                })
                // 二次请求时回调
                .requestCustomRationaleListener(new Wrapper.PermissionCustomRationaleListener() {
                    @Override
                    public void permissionCustomRationale(int code) {
                        new AlertDialog.Builder(TestBaseActivity.this)
                                .setMessage("通讯录权限申请：\n我们需要您开启通讯录权限(in fragment with annotation)")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Permissions4M.get(TestBaseActivity.this)
                                                .requestOnRationale()
                                                .requestPermissions(Manifest.permission.CALL_PHONE)
                                                .requestCodes(CALL_PHONE)
                                                .request();
                                    }
                                })
                                .show();
                    }
                })
                // 权限完全被禁时回调函数中返回 intent 类型（手机管家界面）
                .requestPageType(Permissions4M.PageType.MANAGER_PAGE)
                // 权限完全被禁时回调函数中返回 intent 类型（系统设置界面）
                //.requestPageType(Permissions4M.PageType.ANDROID_SETTING_PAGE)
                // 权限完全被禁时回调，接口函数中的参数 Intent 是由上一行决定的
                .requestPage(new Wrapper.PermissionPageListener() {
                    @Override
                    public void pageIntent(int i, final Intent intent) {
                        new AlertDialog.Builder(TestBaseActivity.this)
                                .setMessage("读取通讯录权限申请：\n我们需要您开启读取通讯录权限(in activity with listener)")
                                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        startActivity(intent);
                                    }
                                })
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.cancel();
                                    }
                                })
                                .show();
                    }

                })
                .request();
    }


    private void rxRequest() {
        RxPermissions rxPermissions = new RxPermissions(this);
        rxPermissions.request(/*android.Manifest.permission.WRITE_EXTERNAL_STORAGE,*/ android.Manifest.permission.CALL_PHONE
                /*android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION,
                android.Manifest.permission.READ_PHONE_STATE, android.Manifest.permission.RECORD_AUDIO, android.Manifest.permission.CAMERA*/
        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(@NonNull Boolean aBoolean) throws Exception {
                if (aBoolean) {//true表示获取权限成功（注意这里在android6.0以下默认为true）
                    Log.i("==--", "权限成功");
                    Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:15213355341"));
                    startActivity(intent);
                } else {
                    Log.i("==--", "权限被拒绝");
                }
            }
        });
    }


}
